package com.example.demo.controller;

import com.example.demo.error.Result;
import com.example.demo.error.ResultGenerator;
import com.example.demo.exception.BusinessException;
import com.example.demo.pojo.LoginRequest;
import com.example.demo.pojo.RegisterRequest;
import com.example.demo.pojo.UserLog;
import com.example.demo.service.UserLogService;
import com.example.demo.util.CaptchaUtil;
import com.example.demo.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author admin
 */

@RestController
@RequestMapping("/api/auth")
public class UserLogController {
    @Autowired
    private UserLogService userService;
    // 使用Session存储验证码
    private static final String CAPTCHA_SESSION_KEY = "CAPTCHA_TEXT";

    /**
     * 注册
     * @param request
     * @return
     */
    @PostMapping("/register")
    public Result<?> register(@RequestBody RegisterRequest request) {
        try {
            if (request.getUsername() == null || request.getPassword() == null || request.getEmail() == null) {
//                return ResponseEntity.badRequest().body(new ErrorResponse("所有字段均为必填"));
                return ResultGenerator.genFailResult("所有字段均为必填");
            }
            UserLog user = userService.register(
                    request.getUsername(),
                    request.getPassword(),
                    request.getEmail(),
                    request.getPhone()
            );
//            return ResponseEntity.ok(new AuthResponse("注册成功", user));
            return ResultGenerator.genSuccessResult("注册成功");
        } catch (RuntimeException e) {
//            return ResponseEntity.badRequest().body(new ErrorResponse(e.getMessage()));
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

    /**
     * 密码登录
     * @param request
     * @return
     */
    @PostMapping("/login")
    public Result<?> login(@RequestBody LoginRequest request, HttpSession session) {
        if (request.getUsername() == null || request.getPassword() == null) {
                return ResultGenerator.genFailResult("用户名和密码均为必填");
            }
            UserLog user = userService.login(
                    request.getUsername(),
                    request.getPassword()
            );
        String sessionCaptcha = (String) session.getAttribute(CAPTCHA_SESSION_KEY);
        if (sessionCaptcha == null || !sessionCaptcha.equalsIgnoreCase(request.getCaptcha())) {
            return ResultGenerator.genFailResult("验证码错误");
        }
        // 验证码正确后清除session中的验证码
        session.removeAttribute(CAPTCHA_SESSION_KEY);
        String token = JwtUtil.generateToken(user.getUsername());
        Map<String, Object> response = new HashMap<>();
        response.put("token", token);
        response.put("username", user.getUsername());
        response.put("email", user.getEmail());
        return ResultGenerator.genSuccessfulResult(response,"登录成功");
    }

    /**
     * 验证码登录
     */
    @PostMapping("/loginPhone")
    public Result<?> loginByPhone(@RequestBody LoginRequest request) {
        if (request.getUsername() == null || request.getPhoneNum() == null) {
            throw new BusinessException(500,"使用手机验证码登录时，手机验证码或用户名不能为空");
        }
        int num = userService.loginByPhone(request);
        return ResultGenerator.genSuccessfulResult(num,"验证码发送成功");
    }
    /***
     * 验证码登录校验
     */
    @PostMapping("/checkCode")
    public Result<?> checkCode(@RequestBody LoginRequest request) {
        UserLog userLog = userService.checkCode(request);
        String token = JwtUtil.generateToken(userLog.getUsername());
        Map<String, Object> response = new HashMap<>();
        response.put("username", userLog.getUsername());
        response.put("email", userLog.getEmail());
        response.put("token", token);
        return ResultGenerator.genSuccessfulResult(response,"登录成功");
    }
    /***
     * 修改用户
     * @param request
     * @return
     */
    @PostMapping("/update")
    public Result<?> update(@RequestBody RegisterRequest request) {
        if (request.getUsername() == null || request.getPassword() == null || request.getEmail() == null) {
            throw new BusinessException(500,"缺少字段信息");
        }
        int num = userService.update(request);
        return ResultGenerator.genSuccessfulResult(num,"修改成功");
    }

    /**
     * 获取验证码图片
     */
    @GetMapping("/captcha")
    public Result<?> getCaptcha(HttpSession session) {
        Map<String, String> captcha = CaptchaUtil.generateCaptcha();
        session.setAttribute(CAPTCHA_SESSION_KEY, captcha.get("captchaText"));
        Map<String, String> response = new HashMap<>();
        response.put("captchaImage", captcha.get("captchaImage"));
        return ResultGenerator.genSuccessfulResult(response,"验证码生成成功");
//        return ResultGenerator.genSuccessResult(response, "验证码生成成功");
    }
}
